package member

import (
	"context"

	"googee/common/errorx"
	"googee/service/account/rpc/account"
	"googee/service/admin/api/internal/svc"
	"googee/service/admin/api/internal/types"
	"googee/service/user/rpc/user"

	"github.com/dtm-labs/dtmcli/dtmimp"
	"github.com/dtm-labs/dtmgrpc"
	"github.com/zeromicro/go-zero/core/logx"
)

type MemberAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewMemberAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *MemberAddLogic {
	return &MemberAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *MemberAddLogic) MemberAdd(req *types.AddMemberReq) (resp *types.AddMemberResp, err error) {
	logx.Infof("==================================================> MemberAdd")
	accountRpcBusiServer, err := l.svcCtx.Config.Account.BuildTarget()
	dtmimp.FatalIfError(err)

	name := user.RegisterNameRequest{
		Name:     req.Name,
		Password: req.Password,
		Avatar:   &req.Avatar,
		Gender:   &req.Gender,
		Nickname: &req.Nickname,
	}
	u, err := l.svcCtx.User.RegisterUserByName(l.ctx, &name)

	if err != nil {
		return nil, errorx.NewDefaultError("删除会员失败")
	}

	gid := dtmgrpc.MustGenGid(l.svcCtx.Config.DtmServer)
	msg := dtmgrpc.NewMsgGrpc(l.svcCtx.Config.DtmServer, gid).Add(
		accountRpcBusiServer+"/account.Account/createAccount", &account.IdRequest{
			Id: u.Id})

	err = msg.Submit()
	dtmimp.FatalIfError(err)

	return &types.AddMemberResp{
		Code:    "000000",
		Message: "创建会员信息成功",
	}, nil
}
